package com.baidu.tcpThreadPoolDemo1;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {
    //0.创建私有的线程池对象
    private static ThreadPoolExecutor pool = new ThreadPoolExecutor(
            2,
            4,
            10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(2),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) {
        //1.创建服务端socket
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(9090);

            //2.循环调用accept方法看是否有新的客户端链接
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println(socket.getRemoteSocketAddress() + " 已链接!");

                //3.一旦有新的链接 就创建线程任务
                ServerRunnable serverRunnable = new ServerRunnable(socket);

                //4.将任务加入线程池
                pool.execute(serverRunnable);
            }

        } catch (Exception e) {
            System.out.println(" 已下线");
        }
    }
}
